package com.dong.mjblog.controller;

import com.dong.mjblog.dto.CommentDTO;
import com.dong.mjblog.dto.CommentListDTO;
import com.dong.mjblog.dto.ResultDTO;
import com.dong.mjblog.entity.CommentEntity;
import com.dong.mjblog.entity.UserEntity;
import com.dong.mjblog.enums.CommentTypeEnum;
import com.dong.mjblog.exception.CustomizeErrorCode;
import com.dong.mjblog.exception.CustomizeException;
import com.dong.mjblog.service.impl.CommentImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author:dxf
 * @Date:2020/11/16-11-16 22:03
 */
@Controller
public class CommentController {

    @Autowired
    private CommentImpl commentImpl;

    @ResponseBody
    @RequestMapping(value = "/comment",method = RequestMethod.POST)
    public ResultDTO comment(@RequestBody CommentDTO commentDTO,
                             HttpServletRequest request){


        if(commentDTO == null || StringUtils.isBlank(commentDTO.getContent())){
            throw new CustomizeException(CustomizeErrorCode.CONTENT_IS_EMPTY);
        }
        String content = commentDTO.getContent();
        UserEntity user = (UserEntity)request.getSession().getAttribute("user");
        if(user == null){
            return ResultDTO.errorOf(CustomizeErrorCode.NOT_LOGIN);
        }

        Long timestamp = System.currentTimeMillis()/1000;
        Long parentId = commentDTO.getParentId();
        Integer type = commentDTO.getType();

        if(parentId == null || parentId == 0){
            throw new CustomizeException(CustomizeErrorCode.TARGET_PARAM_NOT_FOUND);
        }
        if(type == null || !CommentTypeEnum.isExist(type)){
            throw new CustomizeException(CustomizeErrorCode.COMMENT_NOT_FOUND);
        }
        CommentEntity comment = new CommentEntity();
        comment.setType(type);
        comment.setContext(content);
        comment.setParentId(parentId);
        comment.setGmtCreate(timestamp);
        comment.setGmtModified(timestamp);
        comment.setCommentator(user.getId());
        comment.setLikeCount(0L);
        commentImpl.comment(comment);
        return  ResultDTO.okOf();
    }


    @ResponseBody
    @RequestMapping(value = "/comment/{id}",method = RequestMethod.GET)
    public ResultDTO index(@PathVariable(name = "id") Long id){
        List<CommentListDTO> commentListDTOS = commentImpl.listByTargetId(id, CommentTypeEnum.COMMENT);
        return ResultDTO.okOf(commentListDTOS);
    }
}
